const response = require("../utils/response");
const router = require("koa-router")();
const {
    handleDatabaseError,
    dealNotEmpty,
    dealNotEmptyArry, paginate,
} = require("../utils/dberrordeal");
const Joi = require("joi");
const { order } = require("../models/order");
const validationMiddleware = require("../middleware/validate");
const dayjs = require("dayjs");
const { bill, product } = require("../models/bill");
const { supplier } = require("../models/supplier");
const { supplierProduct } = require("../models/supplierProduct");
const axios = require('axios');
const rulesSchema = {
    "/addOrder": Joi.object({
        uid: dealNotEmptyArry("客户订单号"),
        sid: dealNotEmptyArry("供应商订单号"),
    }),
    "/putOrder": Joi.object({
        id: dealNotEmpty("订单号"),
        uid: dealNotEmptyArry("客户订单号"),
        sid: dealNotEmptyArry("供应商订单号"),
    }),
    "/getOrder": Joi.object({
        id: dealNotEmpty("订单号"),

    }),
    "/delOrder": Joi.object({
        id: dealNotEmpty("订单号"),
    }),
};

router.get("/getOrderRandomCode", async (ctx, next) => {
    let code;
    let isUnique = false;
    while (!isUnique) {
        code =
            "KFUSR" +
            dayjs().format("YYYYMMDD") +
            "-" + dayjs().format("HHmm")

        await order.findOne({ code: code }).then((res) => {
            if (!res) {
                isUnique = true;
            }
        });
    }

    response.success(ctx, { data: code });
});

router.post(
    "/addOrder",
    validationMiddleware(rulesSchema),
    async (ctx, next) => {
        let data = ctx.request.body;
        data.createTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
        await order
            .create(data)
            .then(() => {
                response.success(ctx, {});
            })
            .catch((err) => {
                handleDatabaseError(ctx, err, "关联订单已存在");
            });

    }
);
router.get(
    "/orderlList",
    async (ctx, next) => {
        let data = ctx.request.body;
        let params = ctx.request.query;
        let query = {};
        let orders = await paginate(order, query, params, [{
            path: 'sid',
            model: 'supplier'
        }, {
            path: 'uid',
            model: 'bill'
        }],  { createTime: -1 });
        response.success(ctx, {
            data: {
                list: orders.results,
                total: orders.total,
            },
        });
    }
)
router.post("/getOrder", async (ctx, next) => {
    let id = ctx.request.body.id;
    await order
        .findOne({
            _id: id,
        })
        .then((res) => {
            response.success(ctx, { data: res });
        })
        .catch((err) => {
            handleDatabaseError(ctx, err);
        });
});

router.post(
    "/putOrder",
    validationMiddleware(rulesSchema),
    async (ctx, next) => {
        let data = ctx.request.body;
        data.createTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
        await order
            .findOneAndUpdate({ _id: data.id }, { $set: data })
            .then(() => {
                response.success(ctx, {});
            })
            .catch((err) => {
                console.log(err);
                handleDatabaseError(ctx, err, "订单已存在");
            });
    }
);



router.post("/delOrder", validationMiddleware(rulesSchema), async (ctx, next) => {
    let id = ctx.request.body.id;
    await order
        .findOneAndDelete({ _id: id })
        .then(() => {
            response.success(ctx, {});
        })
        .catch((err) => {
            handleDatabaseError(ctx, err);
        });
});

router.get("/homeData", async (ctx, next) => {
    // 新增统计项
    const [
        totalBillAmount,
        totalSupplierAmount,
        totalBillNum,
        totalSupplierNum,
        billProductTop10

    ] = await Promise.all([
        await bill.aggregate([
            {
                $group: {
                    _id: null,
                    totalAmount: { $sum: "$amount" }
                }
            },
            {
                $project: {
                    _id: 0,
                    totalAmount: 1
                }
            }
        ]),
        await supplier.aggregate([
            {
                $group: {
                    _id: null,
                    totalAmount: { $sum: "$supplierAmount" }
                }
            },
            {
                $project: {
                    _id: 0,
                    totalAmount: 1
                }
            }
        ]),
        await bill.countDocuments(),
        await supplier.countDocuments(),
        //统计客户产品前十名按照pid分组关联product表获取产品名称字段，然后按照pid分组，然后按照数量排序，然后取前10条数据
        await bill.aggregate([
            // 展开 product 数组
            { $unwind: "$product" },

            // 将字符串 pid 转换为 ObjectId
            {
                $addFields: {
                    "product.pidObject": { $toObjectId: "$product.pid" }
                }
            },

            // 按新的 pidObject 分组统计销量
            {
                $group: {
                    _id: "$product.pidObject",
                    totalSold: { $sum: "$product.number" }
                }
            },

            // 按销量排序
            { $sort: { totalSold: -1 } },

            // 取前10名
            { $limit: 10 },

            // 连接 products 集合获取产品详情
            {
                $lookup: {
                    from: "products",           // 商品集合名称
                    localField: "_id",          // 当前文档中的 pidObject（已转为 ObjectId）
                    foreignField: "_id",        // products 中的 _id
                    as: "productInfo"
                }
            },

            // 提取 productInfo 中的第一个元素
            {
                $addFields: {
                    productInfo: { $arrayElemAt: ["$productInfo", 0] }
                }
            },

            // 提取商品名称，并设置默认值防止空值
            {
                $addFields: {
                    productName: { $ifNull: ["$productInfo.name", "未知商品"] }
                }
            },

            // 可选：删除不需要的字段
            {
                $project: {
                    productInfo: 0
                }
            }
        ])






    ]);



    function calculateuserPieChartData() {
        return new Promise(async (resolve, reject) => {
            const totalAmountPerName = await bill.aggregate([
                {
                    $group: {
                        _id: "$name",
                        totalAmount: { $sum: "$amount" }
                    }
                }
            ]);

            const totalAmount = await bill.aggregate([
                {
                    $group: {
                        _id: null,
                        totalAmount: { $sum: "$amount" }
                    }
                },
                {
                    $project: {
                        _id: 0,
                        totalAmount: 1
                    }
                }
            ]);

            const totalAmountValue = totalAmount.length > 0 ? totalAmount[0].totalAmount : 0;

            const pieChartData = totalAmountPerName.map(item => ({
                name: item._id,
                value: item.totalAmount,
                percentage: (item.totalAmount / totalAmountValue * 100).toFixed(2) + '%'
            }));
            resolve(pieChartData);

        })

    }

    function calculatesupplierPieChartData() {
        return new Promise(async (resolve, reject) => {
            const totalAmountPerName = await supplier.aggregate([
                {
                    $group: {
                        _id: "$supplierName",
                        totalAmount: { $sum: "$supplierAmount" }
                    }
                }
            ]);

            const totalAmount = await supplier.aggregate([
                {
                    $group: {
                        _id: null,
                        totalAmount: { $sum: "$supplierAmount" }
                    }
                },
                {
                    $project: {
                        _id: 0,
                        totalAmount: 1
                    }
                }
            ]);

            const totalAmountValue = totalAmount.length > 0 ? totalAmount[0].totalAmount : 0;

            const pieChartData = totalAmountPerName.map(item => ({
                name: item._id,
                value: item.totalAmount,
                percentage: (item.totalAmount / totalAmountValue * 100).toFixed(2) + '%'
            }));
            resolve(pieChartData);

        })

    }


    const userPieChartData = await calculateuserPieChartData()
    const supplierPieChartData = await calculatesupplierPieChartData()

    response.success(ctx, {
        data: {
            userPieChartData,
            supplierPieChartData,
            totalBillAmount,
            totalSupplierAmount,
            totalBillNum,
            totalSupplierNum,
            billProductTop10
        }
    });
});

module.exports = router;


